﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Code.BLL;
using QianBuo.Lottery.Web.Areas.Manage.Models;
using Code.Models;

namespace QianBuo.Lottery.Web.Areas.Manage.Controllers
{
    [Authorize(Roles = "Manager_Lottery_Open")]
    public class SchemeController : BaseController
    {
        public ActionResult Index(SchemeModels.SchemeModel model)
        {
            if (model == null)
                model = new SchemeModels.SchemeModel();
            if (model.Serch == null)
                model.Serch = new SchemeManage.SchemeSerchModel();

            var states = model.States as List<SelectListItem>;
            states.Add(new SelectListItem { Text = "中奖方案", Value = "Win" });
            states.Add(new SelectListItem { Text = "未中奖方案", Value = "NoWin" });
            if ("Win" == Request.Form["Serch.State"])
                model.Serch.IsWin = true;
            else if ("NoWin" == Request.Form["Serch.State"])
                model.Serch.IsWin = false;

            if (!string.IsNullOrEmpty(model.Serch.IssueName) && !model.Serch.LotteryType.HasValue)
            {
                ModelState.AddModelError("Error", "安期号查找必须指定彩种");
            }
            else
            {

                var SM = new SchemeManage();
                var schemes = SM.GetSchemeDetail(model.Serch, null);
                model.SumCount = schemes.Count();
                if (model.SumCount > 0)
                {
                    model.SumSchems = schemes.GroupBy(p => 1).Select(p => new SchemeManage.SchemeItemModel
                        {
                            SchemeMoney = p.Sum(pp => pp.SchemeMoney),
                            SchemeCount = p.Sum(pp => pp.SchemeCount),
                            Multiple = p.Sum(pp => pp.Multiple),
                            WinMoney = p.Sum(pp => pp.WinMoney)
                        }).First();
                    model.Schemes = schemes.OrderByDescending(p => p.AddTime).Skip(model.PageSize * (model.Page - 1)).Take(model.PageSize).ToArray();
                }
            }

            return View(model);
        }

        public ActionResult ChuPiao(Guid id)
        {
            var red=Request["returnurl"]??Url.Action("Index");
            string msg=null;
            var SM = new SchemeManage();
            var scheme = SM.Select(s => s.FirstOrDefault(p => p.ID == id));
            if (scheme == null)
                msg = "方案不存在";
            else if (scheme.State != (short)SchemeState.Normal)
                msg = "方案为" + ((SchemeState)scheme.State).GetName() + ",无法处理";
            else
            {
                try
                {
                    msg = SM.OutBill(scheme) > 0 ? "出票成功" : "出票失败！";
                }
                catch (AppException e)
                {
                    msg = e.Message;
                }
                catch (Exception)
                {
                    msg = "系统错误，请稍后再试！";
                }

            }
            return Content(string.Format("<script>alert('{0}');location.href='{1}';</script>",msg,red));
        }

        public ActionResult Cancle(Guid id,SchemeState type)
        {
            var red = Request["returnurl"] ?? Url.Action("Index");
            if (!ModelState.IsValid)
                return Redirect(red);
            string msg = null;
            var SM = new SchemeManage();
            try
            {
                msg = SM.CancleScheme(id, type) > 0 ? "撤销成功" : "系统错误，请稍后再试！";
            }
            catch (AppException e)
            {
                msg = e.Message;
            }
            catch (Exception)
            {
                msg = "系统错误，请稍后再试！";
            }
            return Content(string.Format("<script>alert('{0}');location.href='{1}';</script>", msg, red));
        }

        public ActionResult PaiJiang(Guid id)
        {
            var red = Request["returnurl"] ?? Url.Action("Index");
            string msg = null;
            var SM = new SchemeManage();
            try
            {
                int rs= SM.BuJian(id);
                if(rs<0)
                    msg="系统错误，请稍后再试！";
                else if(rs>0)
                    msg="方案派将成功，该方案中奖了！";
                else
                    msg="方案派将成功，但方案未中奖";
            }
            catch (AppException e)
            {
                msg = e.Message;
            }
            catch (Exception)
            {
                msg = "系统错误，请稍后再试！";
            }
            return Content(string.Format("<script>alert('{0}');location.href='{1}';</script>", msg, red));
        }

        public ActionResult Detail(Guid id)
        {
            var SM = new SchemeManage();

            var model = new SchemeModels.DetailModel();
            model.Scheme = SM.GetSchemeDetail(new SchemeManage.SchemeSerchModel { ID = id }, null).FirstOrDefault();
            if (model.Scheme == null)
                ModelState.AddModelError("Error", "不存在该方案");
            else
            {
                model.Plays = SM.GetSchemePlays(id).ToArray();
                if (model.Scheme.State == (short)SchemeState.Opened)
                    model.WinMoneys = SM.GetSchemeWinMoneys(id).ToArray();
                model.Plays.Each(p => { if (!string.IsNullOrEmpty(p.WinNumber))p.WinNumber = p.WinNumber.Replace("&", "、"); });
                if (model.Scheme.IsChaseTask)
                {
                    var chaseID=SM.Select(s=>s.Where(p=>p.ID==id).Select(p=>p.ChaseTask_Detail.ChaseTaskID).FirstOrDefault());
                    model.ChaseTaskDetailList = new ChaseManage().GetChaseTaskDetail(chaseID,null);
                }
            }
            return View(model);
        }

    }
}
